package com.liu.community.redis;/*
 *@Author:Liu Xing-zhi
 *Description:
 *Date:Crated in 16:05 2021/11/11
 */

import com.liu.community.exception.CustomerException;
import com.liu.community.exception.ErrorCode;
import com.liu.community.pojor.TagResponseDto;
import com.liu.community.mapper.TagPesponseDtoMapper;
import com.liu.community.utils.StringUtilByLike;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class QuestionRedis {


    @Autowired
    private TagPesponseDtoMapper dtoMapper ;
    @Autowired
    private RedisTemplate redisTemplate;

    //根据tag标签查询问题
    public TagResponseDto getTag(String tag){
        //先去Redis缓存里查询，看是否有数据
        ValueOperations opsForValue = redisTemplate.opsForValue();
        //看有效时间是否结束
        Long hadTime = redisTemplate.getExpire(tag);
        log.info("剩余时间{}",hadTime);
        int   time = Math.toIntExact(hadTime);
        TagResponseDto responseDto = (TagResponseDto) opsForValue.get(tag);
        log.info("TagResponseDto data in redis is {}",responseDto);
        if (responseDto  == null  || time <= 0 ){
            //Redis没有数据,从数据库拿取
            String search = StringUtilByLike.getSearch(tag);
            if ("JavaScript".equalsIgnoreCase(tag) || "springMVC".equalsIgnoreCase(tag) ||
                    "springBoot".equalsIgnoreCase(tag) || "springCloud".equalsIgnoreCase(tag)){
                //tag标签是javaScript,springMVC等，不走 where tag = #{tag}
                responseDto = dtoMapper.queryCommentAndLikeCount(search);
            }else {
                responseDto = dtoMapper.queryCommentAndCount(tag);
            }
            opsForValue.set(tag,responseDto,60*60*3, TimeUnit.SECONDS);//设置60*60*3过期时间 3小时后过期
            log.info("TagResponseDto data in mysql  is {}",responseDto);//再讲从数据库里查出来的数据，存入Redis缓存中
        }
        return  responseDto;
    }
}
